<?php

namespace addons\resources\user\controller;

class Video extends \web\user\controller\AddonUserBase {
    
    public function video_list(){
        $m = new \addons\resources\model\VideoClass();
        $list = $m->getDataList();
        $this->assign('class_id',$list);
        return $this->fetch();
    }

    /**
     * 图片资源文件信息
     */
    public function index() {
        $folder = $this->_get('folder');
        $checktype = $this->_get('checktype');
        $limit_num = $this->_get('limit_num');
        $this->assign('folder', $folder);
        $this->assign('checktype', $checktype);
        $res_type = 1;
        $this->assign('res_type', $res_type);
        $is_cut = 0;
        $this->assign('is_cut', $is_cut);
        $this->assign('limit_num', $limit_num); //选取limit
        $this->assign('host', config('aliyunoss')['host']); //选取limit
//         return $this->fetch('base_video');
        return $this->fetch('ali_video');
    }
    

    public function loadList() {
        $keyword = $this->_get('keyword');
        $video_class_id = $this->_get('video_class_id');
        $m = new \addons\resources\model\Resources();
        $filter = 'res_type = 3';
        if($video_class_id != ''){
            $filter .=' and class_id='.$video_class_id;
        }
        if ($keyword != null) {
            $filter .= ' and alias_name like \'%' . $keyword . '%\'';
        }
        $total = $m->getTotal($filter);
        $data = $m->getVideoList($this->getPageIndex(), $this->getPageSize(), $filter);
        return $this->toDataGrid($total, $data);
    }
    
    public function edit(){
        if(IS_POST){
            $data['id'] = $this->_post('id');
            $data['alias_name'] = $this->_post('alias_name');
            $data['class_id'] = intval($this->_post('class_id'));
            $data['video_time'] = $this->_post('video_time');
//            $data['share_send'] = intval($this->_post('share_send'));
            $m = new \addons\resources\model\Resources();
            $ret = $m->save($data);
            if($ret > 0){
                return $this->successData();
            }else{
                return $this->failData('设置失败');
            }
        }else{
            $this->assign('id',$this->_get('id'));
            $m = new \addons\resources\model\VideoClass();
            $list = $m->getDataList();
            $this->assign('class_id',$list);
            $this->setLoadDataAction('loadData');
            return $this->fetch();
        }
    }
    
    public function loadData($id){
        $m = new \addons\resources\model\Resources();
        $data = $m->getDetail($id);
        return $data;
    }
    
    
    /**
     * 视频分类
     * @return type
     */
    public function class_list(){
        return $this->fetch();
    }
    
    public function loadClassList(){
        $keyword = $this->_get('keyword');
        $filter = '';
        if ($keyword != null) {
            $filter = 'video_class_name like \'%' . $keyword . '%\'';
        }
        $m = new \addons\resources\model\VideoClass();
        $total = $m->getTotal($filter);
        $rows = $m->getDataList($this->getPageIndex(), $this->getPageSize(), $filter);
        return $this->toDataGrid($total, $rows);
    }
    
    public function edit_class(){
        $m = new \addons\resources\model\VideoClass();
        if (IS_POST) {
            $data['id'] = $this->_post('id');
            $data['video_class_name'] = $this->_post('video_class_name');
            $data['is_allow'] = $this->_post('is_allow');
            $data['order_index'] = $this->_post('order_index');
            $data['update_time'] = NOW_DATETIME;
            $id = $data['id'];
            try {
                if (empty($id)) {
                    $ret = $m->add($data);
                } else {
                    $ret = $m->save($data);
                }
                return $this->successData();
            } catch (\Exception $e) {
                return $this->failData($e->getMessage());
            }
        } else {
            $id = $this->_get('id');
            $this->assign('id', $id);
            $this->assign('order_index', $m->getNewOrderIndex()); //排序
            $this->setLoadDataAction('loadClassData');
            return $this->fetch();
        }
    }

    function loadClassData($id){
        $m = new \addons\resources\model\VideoClass();
        $data = $m->getDetail($id);
        return $data;
    }


    


    private function gmt_iso8601($time) {
        $dtStr = date("c", $time);
        $mydatetime = new \DateTime($dtStr);
        $expiration = $mydatetime->format(\DateTime::ISO8601);
        $pos = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);
        return $expiration."Z";
    }


    public function loadTencentAccess(){
        echo (new \addons\resources\utils\TencentResources())->loadAccess();
    }

    public function loadAccess(){
        $data = config('aliyunoss');
        $id= $data['AccessKeyId'];
        $key= $data['AccessKeySecret'];
        $host = $data['host'];
        // $host的格式为 bucketname.endpoint，请替换为您的真实信息。
        // $callbackUrl为上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实URL信息。
        $callbackUrl = $data['callbackUrl'];
        $dir = 'video/';          // 用户上传文件时指定的前缀。
        $callback_param = array('callbackUrl'=>$callbackUrl, 
            'callbackBody'=>'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}', 
            'callbackBodyType'=>"application/x-www-form-urlencoded");
        $callback_string = json_encode($callback_param);

        $base64_callback_body = base64_encode($callback_string);
        $now = time();
        $expire = 30;  //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问。
        $end = $now + $expire;
        $expiration = $this->gmt_iso8601($end);

        //最大文件大小.用户可以自己设置
        $condition = array(0=>'content-length-range', 1=>0, 2=>1048576000);
        $conditions[] = $condition; 

        // 表示用户上传的数据，必须是以$dir开始，不然上传会失败，这一步不是必须项，只是为了安全起见，防止用户通过policy上传到别人的目录。
        $start = array(0=>'starts-with', 1=>'$key', 2=>$dir);
        $conditions[] = $start; 

        $arr = array('expiration'=>$expiration,'conditions'=>$conditions);
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

        $response = array();
        $response['accessid'] = $id;
        $response['host'] = $host;
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        $response['callback'] = $base64_callback_body;
        $response['dir'] = $dir;  // 这个参数是设置用户上传文件时指定的前缀。
        echo json_encode($response);

    }


    public function base_upload() {
        $is_cut = $this->_post('is_cut');
        $folder = $this->_post('folder');
        $res_type = 3; //类型(1=图片,2=语音,3=视频)                
        $savePath = UPLOADFOLDER . $folder;
        $originalPath = '';
        if (!empty($folder)) {
            if ($is_cut) {
                $originalPath = $savePath . '/' . $this->md_folder . '/'.date('Ymd').'/';
            } else
                $savePath = $savePath . '/'.date('Ymd').'/';
        }
        if ($is_cut)
            $uploadPath = substr($originalPath, 1);
        else
            $uploadPath = substr($savePath, 1);
        $files = $this->request->file();
        foreach ($files as $file) {
            if ($is_cut)
                $ret = $file->move($originalPath, '');
            else
                $ret = $file->move($savePath,'');
            $json = array('success' => false, 'message' => '上传失败！');
            if (!$ret) {// 上传错误提示错误信息                            
                $json = array('success' => false, 'message' => $file->getError());
            } else {// 上传成功                  
                $fileName = $ret->getInfo()['name'];
//                $filePath = $uploadPath . str_replace('\\', '/', $ret->getSaveName());
                $filePath = $uploadPath . str_replace('\\', '/', $fileName);
                $localPath = $_SERVER['DOCUMENT_ROOT'] . $filePath;
                $errmsg = '';
                if (empty($errmsg)) {
                    $m = new \addons\resources\model\Resources();
                    $data = array();
                    $data['res_type'] = $res_type;
                    $data['file_name'] = $fileName;
                    $data['file_size'] = $this->formatBytes($ret->getSize());
//                    $data['new_name'] = basename($ret->getSaveName());
                    $data['new_name'] = $fileName;
                    $data['file_path'] = $filePath;
                    $data['folder'] = $folder;
                    $data['update_time'] = NOW_DATETIME;
                    $id = $m->add($data);
                    if ($id > -1) {
                        $d = array('id' => $id, 'name' => $fileName, 'path' => $filePath);
                        $json = array('success' => true, 'data' => $d);
                    } else {
                        unlink($localPath);
                    }
                } else {
                    unlink($localPath);
                    $json = array('success' => false, 'message' => $errmsg);
                }
            }
        }
        return json_encode($json, JSON_UNESCAPED_UNICODE);
    }


    public function upload() {
        $folder = $this->_post('folder');
        $fileName = $this->_post('filename');
        $filePath = $this->_post('filepath');
        $file_size = $this->_post('filesize');
        $time_long = $this->_post('video_time');
        $data = array();
        if($time_long){
            $data['video_time'] = $time_long;
            // $hour = floor($time_long/3600) ;
            // $hour = $hour>9?$hour:'0'.$hour;
            // $minites = ($time_long/60)%60 ;
            // $minites = $minites>9?$minites:'0'.$minites;
            // $second = ($time_long%60);
            // $second = $second>9?$second:'0'.$second;
            // $data['video_time'] = $hour.':'.$minites.':'.$second;
        }
        $m = new \addons\resources\model\Resources();
        $data['res_type'] = 3;//类型(1=图片,2=语音,3=视频)
        $data['file_name'] = $fileName;
        $data['file_size'] = $file_size;
        $data['new_name'] = $fileName;
        $data['file_path'] = $fileName;
        $data['update_time'] = NOW_DATETIME;
        $id = $m->add($data);  
        if ($id > -1) {
            $d = array('id' => $id, 'name' => $fileName, 'path' => $filePath);
            $json = array('success' => true, 'data' => $d);
        } 
        echo json_encode($json);
    }


    public function del() {
        $id = $this->_get('id');
        $m = new \addons\resources\model\Resources();
        $data = $m->getDetail($id);
        $ret = -1;
        if ($data) {
//            $localPath = $_SERVER['DOCUMENT_ROOT'] . str_replace(array('./'), array('/'), $data['file_path']);
            $ret = $m->deleteData($id);
        }
        if ($ret > 0) {
            $json = array('success' => true, 'message' => '删除成功');
        } else
            $json = array('success' => false, 'message' => '删除失败');
        return $json;
    }

    private function formatBytes($size) {
        $units = array(' B', ' KB', ' MB', ' GB', ' TB');
        for ($i = 0; $size >= 1024 && $i < 4; $i++)
            $size /= 1024;
        return round($size, 2) . $units[$i];
    }

    /**
     * 检查目录是否可写
     * @param  string   $path    目录
     * @return boolean
     */
    protected function checkPath($path) {
        if (is_dir($path)) {
            return true;
        }

        if (mkdir($path, 0755, true)) {
            return true;
        } else {
            $this->error = "目录 {$path} 创建失败！";
            return false;
        }
    }

    /**
     * 创建缩略图并保存
     * @param type $localPath   原文件绝对路径
     * @param type $folderPath  文件夹路径
     * @param type $fileName    图片名称
     * @return boolean
     */
    private function makeThumb($localPath, $folderPath, $fileName) {
        //打开上传的文件
        $image = \think\Image::open($localPath);
        // 检测(创建)目录
        if (false === $this->checkPath($folderPath)) {
            return false;
        }
        $thumbName = $folderPath . $fileName;
        $res = $image->thumb($this->thumb_width, $this->thumb_height)->save($thumbName);
        return $res;
    }

}
